package com.sjsoft.chat.video;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.aphidmobile.flip.FlipViewController;
import com.aphidmobile.flip.FlipViewController.ViewFlipListener;
import com.novoda.imageloader.core.ImageManager;
import com.novoda.imageloader.core.LoaderSettings;
import com.novoda.imageloader.core.OnImageLoadedListener;
import com.sjsoft.adapter.VideoAdapter;
import com.sjsoft.app.video.R;
import com.sjsoft.application.chatVideoApp;
import com.sjsoft.constant.Constant;
import com.sjsoft.model.videoItem;
import com.sjsoft.video.LoadItemsVideo;
import com.sjsoft.video.loadBillingInfor;
import com.sjsoft.webservice.UtilsJson;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;


public class ListVideo extends Activity implements Constant {
		
	
	private String mExtendId;
	private VideoAdapter adapter;
	private static ImageManager GLOBAL_IMAGE_MANAGER = null;
	private boolean loadMore = false;
	private Context context;
	private videoItem _currentDetail = null;
	
	private chatVideoApp application;
	
	private static void setupImageManager(Context application) {
		if (GLOBAL_IMAGE_MANAGER == null) {
			LoaderSettings settings = new LoaderSettings.SettingsBuilder().withDisconnectOnEveryCall(true).build(application);
			GLOBAL_IMAGE_MANAGER = new ImageManager(application, settings);
		}
	}

	public static final ImageManager getImageManager() {
		return GLOBAL_IMAGE_MANAGER;
	}
	
	private FlipViewController flipView;
	
	private OnImageLoadedListener imageLoadedListener;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	
//    	setContentView(R.layout.content_layout);
    	application = (chatVideoApp)getApplicationContext();
    	setupImageManager(getApplicationContext());
    	LayoutInflater inflater = LayoutInflater.from(this);
    	View layout = inflater.inflate(R.layout.content_layout,null);
    	//flipView = (FlipViewController)layout.findViewById(R.id.id_flipView);
    	context = this;
    	flipView = new FlipViewController(this);
    	//adapter = new VideoAdapter(this);
    	
    	imageLoadedListener = new OnImageLoadedListener() {
			@Override
			public void OnImageLoaded(ImageView view) {

				//Since the listener monitors the progress globally, We have to verify that the ImageView instance is the one inside our flip animation
				if (view.getId() == R.id.img_personal1 || view.getId() == R.id.img_personal2) {
					// Another approach is to use the page index, which should be simpler for most scenarios.
					Object tag = view.getTag(R.id.tag_async_image_view_position);
					if (tag instanceof Integer) {
						flipView.refreshPage((Integer) tag);
					}
				}
			}
		};
		getImageManager().setOnImageLoadedListener(imageLoadedListener);
		//setContentView(flipView);
    	flipView.setOnViewFlipListener(new ViewFlipListener() {
			
			@Override
			public void onViewFlipped(View arg0, int arg1) {
				// TODO Auto-generated method stub
				VideoAdapter videoAdapter = (VideoAdapter)flipView.getAdapter();			
				
				int nPosSel = flipView.getSelectedItemPosition();
				int nPos = videoAdapter.getCount();
								
				if(nPos == nPosSel +1 && loadMore == false)
				{
					loadMore = true;
					int nNext = videoAdapter.getRealItem();				
					//chatVideoApp.appendLog("get more data at :  " +mExtendId);
					LoadItemsVideo loadVideo = new LoadItemsVideo(arg0.getContext(), mExtendId, nNext, null);
			    	loadVideo.execute();
					//flipView.setSelection(application.nPosFlip);
			
				}
								
					
			}
		});
    	
    	chatVideoApp application = (chatVideoApp)getApplicationContext();
    	int nPosTab = mainTab.mTabHost.getCurrentTab();
    	if(nPosTab != 0)
    	{
    		if(application.arrAdapterInit.size() > nPosTab)
    		{
    			VideoAdapter newAdapter = new VideoAdapter(this);
    			newAdapter.addItems(application.arrAdapterInit.get(nPosTab));
    			updateListVideo(newAdapter);
    		}
    	}
    	//Loading data
    	
    	
    	if(application != null )
    		mExtendId =  application.videoByCategory.get(nPosTab).getExtendId();
    	// Get data via the key    	    
    	
    	
	}
    
    public  void loadMoreData(int nIndex)
    {
    	LoadItemsVideo loadVideo = new LoadItemsVideo(this, mExtendId, nIndex, null);
    	loadVideo.execute();
    }
    
    public void refreshLastest()
    {
    	int nPosSel = flipView.getSelectedItemPosition();
    	flipView.setSelection(nPosSel);
    }
    public void updateListVideo(VideoAdapter newAdapter)
    {
    	
    	if(adapter == null)
    	{
    		adapter = newAdapter;
    		flipView.setAdapter(adapter); 
    		setContentView(flipView);
    	}
    	else
    	{
    		adapter.mergeData(newAdapter);
			adapter.notifyDataSetChanged();
    	}
    	loadMore = false;
    }
    @Override
	protected void onResume() {
		super.onResume();
		flipView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		flipView.onPause();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		getImageManager().getCacheManager().clean();
		getImageManager().getFileManager().clean();
		getImageManager().unRegisterOnImageLoadedListener(imageLoadedListener);
	}
	
	
	private String getImei() {
		TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		if(telephonyManager != null)
			return telephonyManager.getDeviceId();
		
		return null;
	}
	
    public  void startChating(videoItem currentVideo)
	{
    	
    	_currentDetail = currentVideo;
    	mainTab mainTab = (mainTab)getParent();
    	if(mainTab != null)
    	{
    		//load all list chat    		
    		if(currentVideo != null)
    		{
    			
    			String sEmei = getImei();
    			String sExtendId = currentVideo.getExtendId();
    			String sItemId = currentVideo.getVideoId();
    			int amount = currentVideo.getAmount();
    			//check tai khoan    	
    			if(application.nTotalAmount < amount)
    			{    				
    				showDialog();
    			}    			
    			else
    			{
    				application.nTotalAmount -= amount;
    				mainTab.setCurVideo(_currentDetail);
    	   		    mainTab.viewDetail();
    	   		    //payment
    	   		    if(amount > 0)
    	   		    {
    	   		    	loadBillingInfor billing = new loadBillingInfor(context);
    	 				billing.setAmount(amount);
    	 				billing.setExtendId(sExtendId);
    	 				billing.setVideoId(sItemId);
    	 				billing.setImei(sEmei);
    	 				billing.execute();
    	   		    }
	    	   		
    			}
    			
    		}
    		
    	}
	}
    
   /*
    Handler handler_Payment = new Handler() {

        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch(msg.what) {

            case 0:
           	 	showDialog();
                break;         
            }
        }

    };
    */
    public void showDialog()
    {
    	final mainTab mainTab = (mainTab)getParent();
    	AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setMessage("Bạn không đủ US để chát với em này. Bạn có muốn nạp US không?");
		alert.setPositiveButton(getString(R.string.text_ok),

		new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
				mainTab.startPayment();
			}
		});
		alert.setNegativeButton(getString(R.string.text_no),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				});
		alert.show();
    }
    
    /*
    public void analyseVideDetail(String billingJson)
    {
    	    
    	final mainTab mainTab = (mainTab)getParent();
    	String sRequirePay = "0";
    	try {
			JSONArray jsonArray = new JSONArray(billingJson);
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				sRequirePay = jsonObject.getString("requiredPayment");
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
    	
    	int nRequire = Integer.parseInt(sRequirePay);
		if(nRequire == 0)
		{    			    				
   		    mainTab.setCurVideo(_currentDetail);
   		    mainTab.viewDetail();
		}
		else
		{    			
			
			
			handler_Payment.sendEmptyMessage(0);
			
		}
		
    }
    */
		
}
